package edu.ncsu.csc.itrust.action;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import edu.ncsu.csc.itrust.beans.AllergyBean;
import edu.ncsu.csc.itrust.beans.DrugInteractionBean;
import edu.ncsu.csc.itrust.beans.MedicationBean;
import edu.ncsu.csc.itrust.beans.OverrideReasonBean;
import edu.ncsu.csc.itrust.beans.PrescriptionBean;
import edu.ncsu.csc.itrust.beans.PrescriptionReportBean;
import edu.ncsu.csc.itrust.beans.forms.EditOfficeVisitForm;
import edu.ncsu.csc.itrust.dao.DAOFactory;
import edu.ncsu.csc.itrust.dao.mysql.AllergyDAO;
import edu.ncsu.csc.itrust.dao.mysql.DrugInteractionDAO;
import edu.ncsu.csc.itrust.dao.mysql.NDCodesDAO;
import edu.ncsu.csc.itrust.dao.mysql.OfficeVisitMedicationDAO;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.exception.iTrustException;
import edu.ncsu.csc.itrust.validate.EditOfficeVisitValidator;


/**
 * Edits a patient's prescription information.  Used by hcp-uap/editPrescription.jsp
 * @author Ben Smith
 */
public class EditPrescriptionAction {

	private OfficeVisitMedicationDAO ovmDAO;
	private DrugInteractionDAO drugDAO;
	private AllergyDAO allergyDAO;
	private NDCodesDAO ndcDAO;
	
	/**
	 * Creates a new action by initializing the office visit
	 * database access object.
	 * 
	 * @param factory
	 * @throws iTrustException
	 */
	public EditPrescriptionAction(DAOFactory factory) throws iTrustException {
		this.ovmDAO = factory.getOVMedicationDAO();
		this.drugDAO = factory.getDrugInteractionDAO();
		this.allergyDAO = factory.getAllergyDAO();
		this.ndcDAO = factory.getNDCodesDAO();
	}

	/**
	 * Edits an existing prescription in the database.
	 * 
	 * @param pres The prescription bean that has been changed.
	 * @throws DBException
	 */
	public void editPrescription(PrescriptionBean pres) throws DBException {
		ovmDAO.editPrescription(pres);
	}
	
	public String hasInteraction(String drug, String pid, String startdate, String enddate) throws iTrustException{
		String response = "";
		try {

			SimpleDateFormat original = new SimpleDateFormat("MM/dd/yyyy");
			SimpleDateFormat needed = new SimpleDateFormat("yyyy/MM/dd");
			
			Date start = original.parse(startdate);
			startdate = needed.format(start);
			Date end = original.parse(enddate);
			enddate = needed.format(end);
			
			
			startdate = startdate.replaceAll("/", "-");
			enddate = enddate.replaceAll("/", "-");
			List<PrescriptionReportBean> prBeanList = ovmDAO.getPrescriptionReportsByDate(Long.parseLong(pid), startdate, enddate);
			List<DrugInteractionBean> dBeanList = drugDAO.getInteractions(drug);
			for (PrescriptionReportBean prBean : prBeanList){
				String presDrug = prBean.getPrescription().getMedication().getNDCode();
				for (DrugInteractionBean dBean : dBeanList){
					String intDrug1 = dBean.getFirstDrug();
					String intDrug2 = dBean.getSecondDrug();
					
					if (presDrug.equals(intDrug1) && drug.equals(intDrug2)){
						response += "Currently Prescribed: " + prBean.getPrescription().getMedication().getDescription() + 
						". Start Date: " + prBean.getPrescription().getStartDateStr() 
						+ ", End Date: " + prBean.getPrescription().getEndDateStr() + ". ";
						response += "Interactions: " + prBean.getPrescription().getMedication().getDescription() + " - " + ndcDAO.getNDCode((dBean.getSecondDrug())).getDescription() + ". ";
						response += "Description: " + dBean.getDescription() + "  ";
					} else if (presDrug.equals(intDrug2) && drug.equals(intDrug1)){
						response += "Currently Prescribed: " + prBean.getPrescription().getMedication().getDescription() + ". Start Date: " + prBean.getPrescription().getStartDateStr() 
						+ ", End Date: " + prBean.getPrescription().getEndDateStr() + ". ";
						response += "Interactions: " + prBean.getPrescription().getMedication().getDescription() + " - " + ndcDAO.getNDCode(dBean.getFirstDrug()).getDescription() + ". ";
						response += "Description: " + dBean.getDescription() + "  ";
					}
				}
			}

		} catch (DBException e){
			e.printStackTrace();
			throw new iTrustException(e.getMessage());
		} catch (ParseException e){
			e.printStackTrace();
			throw new iTrustException(e.getMessage());
		}
		return response;
	}
	
	public String  isAllergyOnList(String patMID, String ndcode) throws iTrustException{
		String response = "";
		try {
			List<AllergyBean> allergyList = allergyDAO.getAllergies(Long.parseLong(patMID));
			if (allergyList.isEmpty()) return response;
			MedicationBean medBean = ndcDAO.getNDCode(ndcode);
			if(medBean == null) return response;
			String newDrug = medBean.getDescription();
			for (AllergyBean allergyBean : allergyList){
				String currentAllerDrug = allergyBean.getDescription();
				//Allergy: Aspirin. First Found: 12/20/2008. 
				if (newDrug.equals(currentAllerDrug)){
					response += "Allergy: " + newDrug + ". First Found: " + allergyBean.getFirstFoundStr();
				}
			}
		} catch (DBException e){
			e.printStackTrace();
			throw new iTrustException(e.getMessage());
		}
		return response;
	}
	
	/**
	 * Edit an override reason
	 * 
	 * @param orb The overridereason to be edited
	 * @throws DBException
	 */
	public void editOverrideReason(OverrideReasonBean orb) throws DBException{
		ovmDAO.editOverrideReason(orb);
	}
	
	/**
	 * Adds a prescription to an office visit
	 * 
	 * @param form the information about the prescription
	 * @param ovID the id for the office visit
	 * @throws DBException
	 * @throws FormValidationException
	 */
		
	public void checkAddPrescription(EditOfficeVisitForm form, long ovID) throws DBException,
				FormValidationException {
			if (form.getAddMedID() != null && !"".equals(form.getAddMedID())) {
				new EditOfficeVisitValidator(true).validate(form);
				PrescriptionBean pres = new PrescriptionBean();
				pres.setDosage(Integer.valueOf(form.getDosage()));
				pres.setEndDateStr(form.getEndDate());
				pres.setStartDateStr(form.getStartDate());
				pres.setInstructions(form.getInstructions());
				MedicationBean med = new MedicationBean();
				med.setNDCode(form.getAddMedID());
				pres.setMedication(med);
				pres.setVisitID(ovID);
				
				long presID = ovmDAO.addPrescription(pres);
				
				if(form.getOverrideCodes() != null)
				{
					OverrideReasonBean orBean;
					for(String code : form.getOverrideCodes())
					{
						orBean = new OverrideReasonBean();
						orBean.setPresID(presID);
						orBean.setORCode(code);
						orBean.setDescription(null);
						ovmDAO.addReason(orBean);
					}
					if(form.getOverrideComment() != null && !form.getOverrideComment().equals("")) {
						orBean = new OverrideReasonBean();
						orBean.setPresID(presID);
						orBean.setORCode("00000");
						orBean.setDescription(form.getOverrideComment());
						ovmDAO.addReason(orBean);
					}

				}
					
			}
		}
}
